package gui;

import etc.Coord;
import etc.PlayerStats;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import templates.Tower;
import templates.TowerTemplate;

import network.ServerConnection;

public class GuimapListener implements MouseListener, KeyListener {

	private Guimap gui;
	private Selection selection;
	private PlayerStats ps;
	private ServerConnection sc;
	
	public GuimapListener(Guimap gui, Selection selection, PlayerStats ps, ServerConnection sc) {
		this.ps = ps;
		this.selection = selection;
		this.gui = gui;
		this.sc = sc;
	}
	
	@Override
	public void mouseClicked(MouseEvent mouse) {
		int x = mouse.getX()/Guimap.TILE_WIDTH;
		int y = mouse.getY()/Guimap.TILE_HEIGHT;
		Coord cord = new Coord(x, y);

		if (x<Guimap.MAP_WIDTH && y < Guimap.MAP_HEIGHT) {
			boolean empty = true;
			Tower clicked=null;
			
			for (Tower t: gui.getTowers()) {
				if (t.pos.equals(cord)) {
					selection.set(clicked, Selection.TOWER);
					return;
				}
			}
			
			if (selection.type() == Selection.BUY) {
				TowerTemplate tt = selection.getTemplate();
				if (ps.cash >= tt.cost) {
					sc.send("tower "+ tt.name.replace(' ', '_') +" "+cord.x+" "+cord.y);
				}
			}
		}
	}

	@Override
	public void mouseEntered(MouseEvent arg0) {}

	@Override
	public void mouseExited(MouseEvent arg0) {}

	@Override
	public void mousePressed(MouseEvent arg0) {}

	@Override
	public void mouseReleased(MouseEvent arg0) {}

	@Override
	public void keyPressed(KeyEvent key) {}

	@Override
	public void keyReleased(KeyEvent arg0) {}

	@Override
	public void keyTyped(KeyEvent arg0) {}

}
